import React, { useState } from 'react';
import { 
  Card, 
  Button, 
  Table, 
  Form, 
  Input, 
  Space, 
  message, 
  Popconfirm, 
  Typography,
  Tag,
  Alert,
  Select,
  Tooltip
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EnvironmentOutlined,
  SaveOutlined,
  CloseOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { TextArea } = Input;

interface EnvironmentVariable {
  id: string;
  name: string;
  value: string;
  description?: string;
  type: 'public' | 'secret';
  created_at: string;
  updated_at: string;
}

interface EnvironmentFormData {
  name: string;
  value: string;
  description?: string;
  type: 'public' | 'secret';
}

interface NewRowData {
  id: string;
  name: string;
  value: string;
  description?: string;
  type: 'public' | 'secret';
  isNew: true;
}

const EnvironmentSettings: React.FC = () => {
  const [variables, setVariables] = useState<EnvironmentVariable[]>([
    {
      id: '1',
      name: 'DATABASE_URL',
      value: 'postgresql://user:pass@localhost:5432/db',
      type: 'secret',
      description: '数据库连接地址',
      created_at: '2024-01-15',
      updated_at: '2024-01-15'
    },
    {
      id: '2',
      name: 'API_VERSION',
      value: 'v1.0.0',
      type: 'public',
      description: 'API版本号',
      created_at: '2024-01-10',
      updated_at: '2024-01-20'
    }
  ]);
  
  const [loading, setLoading] = useState(false);
  const [editingKey, setEditingKey] = useState<string | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [showSecretValues, setShowSecretValues] = useState<{[key: string]: boolean}>({});
  const [form] = Form.useForm();

  const handleAdd = async (values: EnvironmentFormData) => {
    try {
      const newVariable: EnvironmentVariable = {
        id: Date.now().toString(),
        ...values,
        created_at: new Date().toISOString().slice(0, 10),
        updated_at: new Date().toISOString().slice(0, 10)
      };
      setVariables(prev => [newVariable, ...prev]);
      message.success('环境变量创建成功');
      setIsAdding(false);
      setEditingKey(null);
      form.resetFields();
    } catch (error: any) {
      message.error('创建失败: ' + error.message);
    }
  };

  const handleSave = async (id: string) => {
    try {
      const values = await form.validateFields();
      setVariables(prev => 
        prev.map(variable => 
          variable.id === id 
            ? { ...variable, ...values, updated_at: new Date().toISOString().slice(0, 10) }
            : variable
        )
      );
      message.success('环境变量更新成功');
      setEditingKey(null);
    } catch (error: any) {
      message.error('更新失败: ' + error.message);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      setVariables(prev => prev.filter(variable => variable.id !== id));
      message.success('环境变量删除成功');
    } catch (error: any) {
      message.error('删除失败: ' + error.message);
    }
  };

  const handleEdit = (record: EnvironmentVariable) => {
    setEditingKey(record.id);
    form.setFieldsValue({
      name: record.name,
      value: record.value,
      description: record.description,
      type: record.type,
    });
  };

  const handleStartAdd = () => {
    setIsAdding(true);
    setEditingKey('new');
    form.resetFields();
    form.setFieldsValue({
      name: '',
      value: '',
      description: '',
      type: 'public',
    });
  };

  const handleSaveNew = async () => {
    try {
      const values = await form.validateFields();
      await handleAdd(values);
    } catch (error) {
      // 表单验证失败
    }
  };

  const handleCancel = () => {
    setEditingKey(null);
    setIsAdding(false);
    form.resetFields();
  };

  const toggleSecretVisibility = (id: string) => {
    setShowSecretValues(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  };

  const tableData = React.useMemo(() => {
    const data = [...variables];
    if (isAdding) {
      const newRow: NewRowData = {
        id: 'new',
        name: '',
        value: '',
        description: '',
        type: 'public',
        isNew: true,
      };
      data.unshift(newRow as any);
    }
    return data;
  }, [variables, isAdding]);

  const columns: ColumnsType<EnvironmentVariable | NewRowData> = [
    {
      title: '变量名',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (text, record) => {
        const isEditing = editingKey === record.id;
        return isEditing ? (
          <Form.Item
            name="name"
            style={{ margin: 0 }}
            rules={[
              { required: true, message: '请输入变量名' },
              { pattern: /^[A-Z_][A-Z0-9_]*$/, message: '变量名只能包含大写字母、数字和下划线，且不能以数字开头' }
            ]}
          >
            <Input placeholder="例如: API_URL" />
          </Form.Item>
        ) : (
          <Space>
            <EnvironmentOutlined style={{ color: '#52c41a' }} />
            <Text code style={{ fontSize: '12px' }}>{text}</Text>
          </Space>
        );
      },
    },
    {
      title: '变量值',
      dataIndex: 'value',
      key: 'value',
      render: (text, record) => {
        const isEditing = editingKey === record.id;
        const isSecret = record.type === 'secret';
        const isVisible = showSecretValues[record.id];
        
        return isEditing ? (
          <Form.Item
            name="value"
            style={{ margin: 0 }}
            rules={[{ required: true, message: '请输入变量值' }]}
          >
            <TextArea 
              rows={2}
              placeholder="请输入变量值" 
            />
          </Form.Item>
        ) : (
          <Space>
            <Text 
              code 
              style={{ 
                fontSize: '12px',
                maxWidth: 200,
                display: 'block',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap'
              }}
            >
              {isSecret && !isVisible ? '••••••••' : text}
            </Text>
            {isSecret && !('isNew' in record) && (
              <Tooltip title={isVisible ? "隐藏" : "显示"}>
                <Button
                  type="text"
                  size="small"
                  icon={isVisible ? <EyeInvisibleOutlined /> : <EyeOutlined />}
                  onClick={() => toggleSecretVisibility(record.id)}
                />
              </Tooltip>
            )}
          </Space>
        );
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type, record) => {
        const isEditing = editingKey === record.id;
        return isEditing ? (
          <Form.Item
            name="type"
            style={{ margin: 0 }}
            rules={[{ required: true, message: '请选择类型' }]}
          >
            <Select style={{ width: 90 }}>
              <Option value="public">公开</Option>
              <Option value="secret">机密</Option>
            </Select>
          </Form.Item>
        ) : (
          <Tag color={type === 'secret' ? 'red' : 'blue'}>
            {type === 'secret' ? '机密' : '公开'}
          </Tag>
        );
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      render: (text, record) => {
        const isEditing = editingKey === record.id;
        return isEditing ? (
          <Form.Item
            name="description"
            style={{ margin: 0 }}
          >
            <Input placeholder="变量描述（可选）" />
          </Form.Item>
        ) : (
          <Text type="secondary" style={{ fontSize: '12px' }}>
            {text || '-'}
          </Text>
        );
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      width: 150,
      render: (text, record) => {
        if ('isNew' in record) return '-';
        return new Date(text).toLocaleString('zh-CN');
      },
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      render: (_, record) => {
        const isEditing = editingKey === record.id;
        
        if (isEditing) {
          return (
            <Space>
              <Button
                type="primary"
                size="small"
                icon={<SaveOutlined />}
                onClick={() => {
                  if ('isNew' in record) {
                    handleSaveNew();
                  } else {
                    handleSave(record.id);
                  }
                }}
              >
                保存
              </Button>
              <Button
                size="small"
                icon={<CloseOutlined />}
                onClick={handleCancel}
              >
                取消
              </Button>
            </Space>
          );
        }

        if ('isNew' in record) {
          return null;
        }
        
        return (
          <Space>
            <Button
              icon={<EditOutlined />}
              size="small"
              onClick={() => handleEdit(record as EnvironmentVariable)}
              disabled={editingKey !== null}
            />
            <Popconfirm
              title="确定要删除这个环境变量吗？"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                icon={<DeleteOutlined />}
                size="small"
                danger
                disabled={editingKey !== null}
              />
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题 */}
      <div style={{ marginBottom: '24px' }}>
        <Title level={3} style={{ margin: 0, marginBottom: '8px' }}>
          <EnvironmentOutlined style={{ marginRight: '8px', color: '#52c41a' }} />
          环境变量管理
        </Title>
        <Paragraph type="secondary">
          管理应用程序的环境变量配置，支持公开和机密变量
        </Paragraph>
      </div>

      <Card>
        <div style={{ marginBottom: '24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Text strong style={{ fontSize: '16px' }}>环境变量列表</Text>
            <br />
            <Text type="secondary" style={{ fontSize: '14px' }}>
              配置应用程序运行时所需的环境变量
            </Text>
          </div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleStartAdd}
            disabled={editingKey !== null}
          >
            添加变量
          </Button>
        </div>

        {/* 提示信息 */}
        <Alert
          message="安全提示"
          description={
            <div>
              <div>• <strong>公开变量</strong>：可以在前端代码中使用，适用于API地址、配置开关等非敏感信息</div>
              <div>• <strong>机密变量</strong>：仅在服务器端使用，适用于密码、密钥等敏感信息</div>
              <div>• 变量名建议使用大写字母和下划线，例如：API_URL、DATABASE_PASSWORD</div>
            </div>
          }
          type="info"
          icon={<InfoCircleOutlined />}
          style={{ marginBottom: '16px' }}
        />

        {editingKey && (
          <Alert
            message={isAdding ? "新增模式" : "编辑模式"}
            description={isAdding ? "正在添加新环境变量，请填写完整信息后保存" : "正在编辑环境变量，请完成编辑或取消后再进行其他操作"}
            type="info"
            showIcon
            closable={false}
            style={{ marginBottom: '16px' }}
          />
        )}

        <Form form={form} component={false}>
          <Table
            components={{
              body: {
                cell: (props: any) => <td {...props} />,
              },
            }}
            columns={columns}
            dataSource={tableData}
            loading={loading}
            rowKey="id"
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
            scroll={{ x: 'max-content' }}
          />
        </Form>
      </Card>
    </div>
  );
};

export default EnvironmentSettings; 